package com.egao.common.component.crawler.haitou;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.egao.common.module.outer.entity.OuterPreach;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.ArrayList;
import java.util.List;

/**
 * 海投网宣讲会爬虫结果处理实现类
 *
 * @author lym
 */
public class HaiTouPipeline implements Pipeline {

    private List<OuterPreach> list;
    private List<OuterPreach> oldList;

    public HaiTouPipeline() {

    }

    public HaiTouPipeline(List<OuterPreach> oldList, List<OuterPreach> list) {
        this.list = list;
        this.oldList = oldList;
    }

    @Override
    public void process(ResultItems resultItems, Task task) {
        // 标题为空不处理
        if (StrUtil.isBlank(resultItems.get("title"))) {
            return;
        }

        // 举办时间为空不处理
        if (StrUtil.isBlank(resultItems.get("holdTime"))) {
            return;
        }

        // 完善举办时间
        resultItems.put("holdTime", resultItems.get("holdTime") + ":00");
        resultItems.put("createTime", resultItems.get("createTime") + ":00");

        // 将结果字符串转换为结果对象
        OuterPreach outerPreach = JSON.parseObject(JSON.toJSONString(resultItems.getAll()), OuterPreach.class);

        List<OuterPreach> listOuterPreache = new ArrayList<>();
        if (oldList.size() > 0) {
            for (OuterPreach preach : oldList) {
                if ((outerPreach.getHoldTime()).compareTo(preach.getHoldTime()) == 0 && outerPreach.getTitle().trim().equals(preach.getTitle().trim()) && outerPreach.getHoldAddress().trim().equals(preach.getHoldAddress().trim()) && outerPreach.getSchoolName().trim().equals(preach.getSchoolName().trim())) {
                    listOuterPreache.add(preach);
                }
            }
        }

        // 内容中去掉海投网功能按键内容
        String content = outerPreach.getContent();
        content = content.replaceAll("交流群", "");
        content = content.replaceAll("投递简历", "");
        content = content.replaceAll("网申投递", "");
        content = content.replaceAll("button", "p");
        outerPreach.setContent(content);

        // 装载结果到结果集合
        if (listOuterPreache.size() == 0) {
            this.list.add(outerPreach);
        }

    }
}
